package com.yzt.zhuju.mvp;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.CallSuper;

import com.yzt.zhuju.base.BaseFragment;
import com.yzt.zhuju.dialog.LoadingDialog;
import com.yzt.zhuju.rx.FragmentEvent;
import com.yzt.zhuju.rx.LifecycleTransformer;
import com.yzt.zhuju.rx.RxUtils;
import com.yzt.zhuju.utils.ReflectUtils;
import com.yzt.p_base.utils.ToastUtil;

import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;



/**
 * <pre>
 *     author : TK
 *     desc   : MVP Fragment，presenter 为 实现类Impl
 * </pre>
 */
public abstract class MVPFragment<P extends BasePresenter> extends BaseFragment implements Contract.IView {
    private final Subject<Integer> lifecycleSubject = PublishSubject.create();
    protected P mPresenter;
    protected LoadingDialog mDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDialog = new LoadingDialog(getContext());
    }

    @CallSuper
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Class<P> presenter = ReflectUtils.getT(getClass(), 0);
        if (presenter != null) {
            try {
                mPresenter = presenter.newInstance();
                mPresenter.attach(this);
            } catch (Exception e) {
            }
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        lifecycleSubject.onNext(FragmentEvent.ON_DESTORY_VIEW);
        if (null != mPresenter) {
            mPresenter.detach();
        }
        super.onDestroyView();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Override
    public void close() {
    }

    @Override
    public void closeImmediately() {
    }

    @Override
    public void showToast(String tip) {
        ToastUtil.showMessage(tip);
    }

    @Override
    public void showLoadingDialog(String tip) {
        mDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        mDialog.dismiss();
    }

    @Override
    public void showErrorToast(String tip) {
        ToastUtil.showMessage(tip);
    }

    @Override
    public <T> LifecycleTransformer<T> bindLifecycle(int event) {
        return RxUtils.bindLifecycle(lifecycleSubject, event);
    }

    @Override
    public <T> LifecycleTransformer<T> bindOnDestroy() {
        return RxUtils.bindLifecycle(lifecycleSubject, FragmentEvent.ON_DESTORY_VIEW);
    }
}
